<template>
  <div class="inbound-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>入库管理</h2>
      <p>管理商品入库操作，包括采购入库、调拨入库、退货入库等</p>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="5">
          <el-input
            v-model="searchForm.inboundNo"
            placeholder="请输入入库单号"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="5">
          <el-select
            v-model="searchForm.type"
            placeholder="入库类型"
            clearable
            @change="handleSearch"
          >
            <el-option label="全部类型" value="" />
            <el-option label="采购入库" value="purchase" />
            <el-option label="调拨入库" value="transfer" />
            <el-option label="退货入库" value="return" />
            <el-option label="其他入库" value="other" />
          </el-select>
        </el-col>
        <el-col :span="5">
          <el-select
            v-model="searchForm.status"
            placeholder="入库状态"
            clearable
            @change="handleSearch"
          >
            <el-option label="全部状态" value="" />
            <el-option label="待入库" value="pending" />
            <el-option label="部分入库" value="partial" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-col>
        <el-col :span="5">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleSearch"
          />
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增入库
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="filteredTableData"
        style="width: 100%"
        v-loading="loading"
        stripe
        border
      >
        <el-table-column prop="inboundNo" label="入库单号" width="150" />
        <el-table-column prop="type" label="入库类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeColor(row.type)">{{ getTypeName(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="supplierName" label="供应商" min-width="120" />
        <el-table-column prop="warehouseName" label="入库仓库" width="120" />
        <el-table-column prop="totalQuantity" label="总数量" width="100" />
        <el-table-column prop="totalAmount" label="总金额" width="120">
          <template #default="{ row }">
            ¥{{ row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusColor(row.status)">{{ getStatusName(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operatorName" label="操作员" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="150" />
        <el-table-column prop="inboundTime" label="入库时间" width="150" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <el-button 
              size="small" 
              type="primary" 
              @click="handleInbound(row)"
              :disabled="row.status === 'completed' || row.status === 'cancelled'"
            >
              入库
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleCancel(row)"
              :disabled="row.status === 'completed' || row.status === 'cancelled'"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalItems"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增入库单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="新增入库单"
      width="800px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库单号" prop="inboundNo">
              <el-input v-model="form.inboundNo" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库类型" prop="type">
              <el-select v-model="form.type" style="width: 100%">
                <el-option label="采购入库" value="purchase" />
                <el-option label="调拨入库" value="transfer" />
                <el-option label="退货入库" value="return" />
                <el-option label="其他入库" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierName">
              <el-select v-model="form.supplierName" style="width: 100%" filterable>
                <el-option label="苹果公司" value="苹果公司" />
                <el-option label="华为技术" value="华为技术" />
                <el-option label="小米科技" value="小米科技" />
                <el-option label="联想集团" value="联想集团" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库仓库" prop="warehouseName">
              <el-select v-model="form.warehouseName" style="width: 100%">
                <el-option label="主仓库" value="主仓库" />
                <el-option label="分仓库A" value="分仓库A" />
                <el-option label="分仓库B" value="分仓库B" />
                <el-option label="临时仓库" value="临时仓库" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" :rows="3" />
        </el-form-item>
        
        <!-- 商品明细 -->
        <el-form-item label="商品明细">
          <el-table :data="form.items" border style="width: 100%">
            <el-table-column prop="productName" label="商品名称" width="150" />
            <el-table-column prop="specification" label="规格" width="120" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="quantity" label="数量" width="100">
              <template #default="{ row, $index }">
                <el-input-number 
                  v-model="row.quantity" 
                  :min="1" 
                  size="small"
                  @change="updateItemTotal($index)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="unitPrice" label="单价" width="100">
              <template #default="{ row, $index }">
                <el-input-number 
                  v-model="row.unitPrice" 
                  :min="0" 
                  :precision="2" 
                  size="small"
                  @change="updateItemTotal($index)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="totalPrice" label="小计" width="100">
              <template #default="{ row }">
                ¥{{ row.totalPrice.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="{ $index }">
                <el-button 
                  size="small" 
                  type="danger" 
                  @click="removeItem($index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 10px;">
            <el-button @click="addItem">添加商品</el-button>
            <span style="float: right; font-weight: bold;">
              总计：¥{{ getTotalAmount().toFixed(2) }}
            </span>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 入库操作对话框 -->
    <el-dialog
      v-model="inboundDialogVisible"
      title="入库操作"
      width="600px"
    >
      <el-form :model="inboundForm" label-width="100px">
        <el-form-item label="入库单号">
          <el-input v-model="inboundForm.inboundNo" disabled />
        </el-form-item>
        <el-form-item label="入库时间">
          <el-date-picker
            v-model="inboundForm.inboundTime"
            type="datetime"
            placeholder="选择入库时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="实际入库">
          <el-table :data="inboundForm.items" border style="width: 100%">
            <el-table-column prop="productName" label="商品名称" width="150" />
            <el-table-column prop="plannedQuantity" label="计划数量" width="100" />
            <el-table-column prop="actualQuantity" label="实际数量" width="120">
              <template #default="{ row }">
                <el-input-number 
                  v-model="row.actualQuantity" 
                  :min="0" 
                  :max="row.plannedQuantity"
                  size="small"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="入库备注">
          <el-input v-model="inboundForm.remark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="inboundDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleInboundSubmit">确认入库</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="入库单详情"
      width="700px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="入库单号">{{ viewData.inboundNo }}</el-descriptions-item>
        <el-descriptions-item label="入库类型">
          <el-tag :type="getTypeColor(viewData.type)">{{ getTypeName(viewData.type) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="供应商">{{ viewData.supplierName }}</el-descriptions-item>
        <el-descriptions-item label="入库仓库">{{ viewData.warehouseName }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusColor(viewData.status)">{{ getStatusName(viewData.status) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="操作员">{{ viewData.operatorName }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ viewData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="入库时间">{{ viewData.inboundTime || '未入库' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ viewData.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
      
      <h4 style="margin: 20px 0 10px 0;">商品明细</h4>
      <el-table :data="viewData.items" border style="width: 100%">
        <el-table-column prop="productName" label="商品名称" />
        <el-table-column prop="specification" label="规格" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="quantity" label="数量" width="100" />
        <el-table-column prop="unitPrice" label="单价" width="100">
          <template #default="{ row }">
            ¥{{ row.unitPrice.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalPrice" label="小计" width="100">
          <template #default="{ row }">
            ¥{{ row.totalPrice.toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const inboundDialogVisible = ref(false)
const viewDialogVisible = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const totalItems = ref(0)
const formRef = ref()

// 搜索表单
const searchForm = reactive({
  inboundNo: '',
  type: '',
  status: '',
  dateRange: []
})

// 表单数据
const form = reactive({
  inboundNo: '',
  type: '',
  supplierName: '',
  warehouseName: '',
  remark: '',
  items: []
})

// 入库操作表单
const inboundForm = reactive({
  inboundNo: '',
  inboundTime: new Date(),
  items: [],
  remark: ''
})

// 查看数据
const viewData = ref({})

// 表单验证规则
const rules = {
  type: [{ required: true, message: '请选择入库类型', trigger: 'change' }],
  supplierName: [{ required: true, message: '请选择供应商', trigger: 'change' }],
  warehouseName: [{ required: true, message: '请选择入库仓库', trigger: 'change' }]
}

// 模拟数据
const tableData = ref([
  {
    id: 1,
    inboundNo: 'IN202401150001',
    type: 'purchase',
    supplierName: '苹果公司',
    warehouseName: '主仓库',
    totalQuantity: 100,
    totalAmount: 799900.00,
    status: 'pending',
    operatorName: '张三',
    createTime: '2024-01-15 09:00:00',
    inboundTime: '',
    remark: '采购iPhone 14 Pro',
    items: [
      {
        productName: 'iPhone 14 Pro',
        specification: '256GB 深空黑色',
        unit: '台',
        quantity: 100,
        unitPrice: 7999.00,
        totalPrice: 799900.00
      }
    ]
  },
  {
    id: 2,
    inboundNo: 'IN202401150002',
    type: 'transfer',
    supplierName: '分仓库A',
    warehouseName: '主仓库',
    totalQuantity: 200,
    totalAmount: 17800.00,
    status: 'partial',
    operatorName: '李四',
    createTime: '2024-01-15 10:30:00',
    inboundTime: '2024-01-15 14:20:00',
    remark: '调拨T恤',
    items: [
      {
        productName: '男士休闲T恤',
        specification: 'L码 白色',
        unit: '件',
        quantity: 200,
        unitPrice: 89.00,
        totalPrice: 17800.00
      }
    ]
  },
  {
    id: 3,
    inboundNo: 'IN202401150003',
    type: 'return',
    supplierName: '客户退货',
    warehouseName: '主仓库',
    totalQuantity: 50,
    totalAmount: 2250.00,
    status: 'completed',
    operatorName: '王五',
    createTime: '2024-01-15 11:15:00',
    inboundTime: '2024-01-15 15:30:00',
    remark: '客户退货入库',
    items: [
      {
        productName: '有机大米',
        specification: '5kg装',
        unit: '袋',
        quantity: 50,
        unitPrice: 45.00,
        totalPrice: 2250.00
      }
    ]
  }
])

// 计算属性
const filteredTableData = computed(() => {
  let data = tableData.value
  
  if (searchForm.inboundNo) {
    data = data.filter(item => 
      item.inboundNo.toLowerCase().includes(searchForm.inboundNo.toLowerCase())
    )
  }
  
  if (searchForm.type) {
    data = data.filter(item => item.type === searchForm.type)
  }
  
  if (searchForm.status) {
    data = data.filter(item => item.status === searchForm.status)
  }
  
  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    const [start, end] = searchForm.dateRange
    data = data.filter(item => {
      const createTime = new Date(item.createTime)
      return createTime >= start && createTime <= end
    })
  }
  
  totalItems.value = data.length
  
  // 分页
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  return data.slice(startIndex, endIndex)
})

// 方法
const handleSearch = () => {
  currentPage.value = 1
}

const handleAdd = () => {
  dialogVisible.value = true
  resetForm()
  generateInboundNo()
}

const handleView = (row) => {
  viewData.value = { ...row }
  viewDialogVisible.value = true
}

const handleInbound = (row) => {
  inboundForm.inboundNo = row.inboundNo
  inboundForm.inboundTime = new Date()
  inboundForm.items = row.items.map(item => ({
    ...item,
    plannedQuantity: item.quantity,
    actualQuantity: item.quantity
  }))
  inboundForm.remark = ''
  inboundDialogVisible.value = true
}

const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消入库单 "${row.inboundNo}" 吗？`,
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value[index].status = 'cancelled'
      ElMessage.success('取消成功')
    }
  } catch {
    ElMessage.info('已取消操作')
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    if (form.items.length === 0) {
      ElMessage.error('请添加商品明细')
      return
    }
    
    const newItem = {
      id: Date.now(),
      ...form,
      totalQuantity: form.items.reduce((sum, item) => sum + item.quantity, 0),
      totalAmount: getTotalAmount(),
      status: 'pending',
      operatorName: '当前用户',
      createTime: new Date().toLocaleString(),
      inboundTime: ''
    }
    
    tableData.value.unshift(newItem)
    ElMessage.success('新增成功')
    dialogVisible.value = false
  } catch {
    ElMessage.error('请检查表单数据')
  }
}

const handleInboundSubmit = () => {
  const item = tableData.value.find(item => item.inboundNo === inboundForm.inboundNo)
  if (item) {
    // 更新实际入库数量
    item.items = inboundForm.items.map(formItem => ({
      ...formItem,
      quantity: formItem.actualQuantity
    }))
    
    // 计算入库状态
    const totalPlanned = inboundForm.items.reduce((sum, item) => sum + item.plannedQuantity, 0)
    const totalActual = inboundForm.items.reduce((sum, item) => sum + item.actualQuantity, 0)
    
    if (totalActual === 0) {
      item.status = 'pending'
    } else if (totalActual < totalPlanned) {
      item.status = 'partial'
    } else {
      item.status = 'completed'
    }
    
    item.inboundTime = inboundForm.inboundTime.toLocaleString()
    item.totalQuantity = totalActual
    item.totalAmount = inboundForm.items.reduce((sum, item) => sum + (item.actualQuantity * item.unitPrice), 0)
    
    ElMessage.success('入库成功')
    inboundDialogVisible.value = false
  }
}

const resetForm = () => {
  Object.assign(form, {
    inboundNo: '',
    type: '',
    supplierName: '',
    warehouseName: '',
    remark: '',
    items: []
  })
  formRef.value?.clearValidate()
}

const generateInboundNo = () => {
  const now = new Date()
  const dateStr = now.toISOString().slice(0, 10).replace(/-/g, '')
  const timeStr = String(now.getTime()).slice(-4)
  form.inboundNo = `IN${dateStr}${timeStr}`
}

const addItem = () => {
  form.items.push({
    productName: '',
    specification: '',
    unit: '',
    quantity: 1,
    unitPrice: 0,
    totalPrice: 0
  })
}

const removeItem = (index) => {
  form.items.splice(index, 1)
}

const updateItemTotal = (index) => {
  const item = form.items[index]
  item.totalPrice = item.quantity * item.unitPrice
}

const getTotalAmount = () => {
  return form.items.reduce((sum, item) => sum + item.totalPrice, 0)
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 辅助方法
const getTypeName = (type) => {
  const map = {
    purchase: '采购入库',
    transfer: '调拨入库',
    return: '退货入库',
    other: '其他入库'
  }
  return map[type] || type
}

const getTypeColor = (type) => {
  const map = {
    purchase: 'primary',
    transfer: 'success',
    return: 'warning',
    other: 'info'
  }
  return map[type] || ''
}

const getStatusName = (status) => {
  const map = {
    pending: '待入库',
    partial: '部分入库',
    completed: '已完成',
    cancelled: '已取消'
  }
  return map[status] || status
}

const getStatusColor = (status) => {
  const map = {
    pending: 'warning',
    partial: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return map[status] || ''
}

// 生命周期
onMounted(() => {
  // 初始化数据
})
</script>

<style scoped>
.inbound-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.table-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-section {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}

@media (max-width: 768px) {
  .inbound-management {
    padding: 10px;
  }
  
  .search-section,
  .table-section {
    padding: 15px;
  }
  
  .el-table {
    font-size: 12px;
  }
}
</style>